/**
 * 策略分配管理模块
 * 
 * 该模块负责管理运费策略与仓库、物流公司之间的分配关系。
 * 支持单个分配和批量分配两种模式，提供灵活的配置管理方式。
 * 
 * 主要功能：
 * - 策略分配查询和筛选（支持按仓库、物流公司、策略名称筛选）
 * - 单个策略分配（一对一关联配置）
 * - 批量策略分配（支持多仓库多物流公司批量配置）
 * - 分配状态管理（启用/禁用）
 * - 策略选择器集成（支持搜索和选择）
 * - 数据验证和错误处理
 * 
 * API调用统一管理：
 * - 查询：window.FreightApp.api.getAssignments() -> POST /strategy-assignment/list
 * - 单个分配：window.FreightApp.api.addAssignment() -> POST /strategy-assignment/assign
 * - 批量分配：window.FreightApp.api.batchAssign() -> POST /strategy-assignment/batch-assign
 * - 策略查询：window.FreightApp.api.getStrategies() -> POST /strategy/list
 * 
 * @author 运费系统团队
 * @version 2.0.0
 * @since 2025-08-29
 * @requires api.js - 统一API服务管理
 */

function useAssignmentManagement() {
    const { ref, reactive, computed } = Vue;
    // 响应式数据
    const assignments = ref([]);
    const filteredAssignments = ref([]); // 用于显示的过滤后数据
    const strategies = ref([]); // 添加策略用于名称查找
    const submitting = ref(false);
    const showAddAssignmentModal = ref(false);
    const showBatchAssignmentModal = ref(false);
    const selectedAssignmentIds = ref([]);

    const assignmentForm = reactive({
        warehouseCode: '',
        logisticsCompanyCode: '',
        strategyId: '',
        status: 1
    });

    const batchAssignmentForm = reactive({
        strategyId: '',
        warehouseCodesText: '',
        logisticsCompanyCodesText: '',
        status: 1
    });

    // 查询表单
    const assignmentQuery = reactive({
        warehouseCode: '',
        logisticsCompanyCode: '',
        strategyName: '',
        status: ''
    });

    /**
     * 加载所有分配
     */
    const loadAssignments = async () => {
        try {
            console.log('加载分配数据...');
            // 加载分配
            const result = await window.FreightApp.api.getAssignments();
            if (result.code === 0) {
                assignments.value = result.data || [];
                filteredAssignments.value = []; // 清空过滤数据，显示全部
                console.log('加载分配成功，数量:', assignments.value.length);
            } else {
                // API失败时清空数据
                assignments.value = [];
                filteredAssignments.value = [];
                window.showMessage('加载分配失败: ' + result.msg, true);
            }

            // 加载策略用于名称查找
            const strategiesResult = await window.FreightApp.api.getStrategies();
            if (strategiesResult.code === 0) {
                strategies.value = strategiesResult.data || [];

                // 在分配中填充策略名称
                (assignments.value || []).forEach(assignment => {
                    const strategy = (strategies.value || []).find(s => s.id === assignment.strategyId);
                    assignment.strategyName = strategy ? strategy.name : '未知策略';
                });
            }
        } catch (err) {
            console.error('加载分配失败:', err);
            // 请求异常时清空数据
            assignments.value = [];
            filteredAssignments.value = [];
            window.showMessage('加载分配失败', true);
        }
    };

    /**
     * 添加新分配
     */
    const addAssignment = () => {
        resetAssignmentForm();
        // 清空策略搜索关键词，避免默认回显
        if (window.vueAppInstance?.strategySearchKeyword) {
            window.vueAppInstance.strategySearchKeyword.value = '';
        }
        showAddAssignmentModal.value = true;
    };

    /**
     * 提交分配表单
     */
    const submitAssignment = async () => {
        const validation = validateAssignmentForm();
        if (!validation.isValid) {
            window.showMessage(validation.errors[0], true);
            return;
        }

        submitting.value = true;
        try {
            // API安全检查
            console.log('🔧 提交分配数据:', assignmentForm);
            console.log('🔧 API对象:', window.FreightApp.api);

            if (!window.FreightApp.api) {
                console.error('❌ API对象未正确导入到assignment.js');
                throw new Error('API对象未正确初始化，请刷新页面重试');
            }

            if (!window.FreightApp.api.addAssignment || typeof window.FreightApp.api.addAssignment !== 'function') {
                console.error('❌ API方法 addAssignment 不存在或不是函数');
                throw new Error('API方法 addAssignment 不存在，请检查window.FreightApp.api.js配置');
            }

            const result = await window.FreightApp.api.addAssignment(assignmentForm);

            console.log('🔧 API调用结果:', result);

            if (result.code === 0) {
                window.showMessage('操作成功');
                closeAssignmentModal();
                loadAssignments();
            } else {
                window.showMessage(result.msg || '操作失败', true);
            }
        } catch (err) {
            console.error('❌ 分配提交错误详情:', err);

            let errorMessage = '提交失败';

            if (err.message.includes('Cannot read properties of undefined')) {
                errorMessage = 'API对象未正确初始化，请刷新页面重试';
            } else if (err.message.includes('is not a function')) {
                errorMessage = 'API方法不存在，请检查系统配置';
            } else {
                errorMessage = err.message || '未知错误';
            }

            window.showMessage(`提交失败: ${errorMessage}`, true);
        } finally {
            submitting.value = false;
        }
    };

    /**
     * 添加批量分配
     */
    const addBatchAssignments = () => {
        resetBatchAssignmentForm();
        // 清空策略搜索关键词，避免默认回显
        if (window.vueAppInstance?.strategySearchKeyword) {
            window.vueAppInstance.strategySearchKeyword.value = '';
        }
        showBatchAssignmentModal.value = true;
    };

    /**
     * 提交批量分配
     */
    const submitBatchAssignment = async () => {
        const validation = validateBatchAssignmentForm();
        if (!validation.isValid) {
            window.showMessage(validation.errors[0], true);
            return;
        }

        submitting.value = true;
        try {
            // API安全检查
            console.log('🔧 提交批量分配数据:', batchAssignmentForm);
            console.log('🔧 API对象:', window.FreightApp.api);

            if (!window.FreightApp.api) {
                console.error('❌ API对象未正确导入到assignment.js');
                throw new Error('API对象未正确初始化，请刷新页面重试');
            }

            if (!window.FreightApp.api.batchAssign || typeof window.FreightApp.api.batchAssign !== 'function') {
                console.error('❌ API方法 batchAssign 不存在或不是函数');
                throw new Error('API方法 batchAssign 不存在，请检查window.FreightApp.api.js配置');
            }

            // 解析仓库编码和物流公司编码
            const warehouseCodes = batchAssignmentForm.warehouseCodesText
                .split(',')
                .map(code => code.trim())
                .filter(code => code);

            const logisticsCompanyCodes = batchAssignmentForm.logisticsCompanyCodesText
                .split(',')
                .map(code => code.trim())
                .filter(code => code);

            const data = {
                strategyId: batchAssignmentForm.strategyId,
                warehouseCodes: warehouseCodes,
                logisticsCompanyCodes: logisticsCompanyCodes,
                status: batchAssignmentForm.status
            };

            const result = await window.FreightApp.api.batchAssign(data);

            console.log('🔧 API调用结果:', result);

            if (result.code === 0) {
                window.showMessage(result.msg || '批量分配成功');
                closeBatchAssignmentModal();
                loadAssignments();
            } else {
                window.showMessage(result.msg || '批量分配失败', true);
            }
        } catch (err) {
            console.error('❌ 批量分配提交错误详情:', err);

            let errorMessage = '提交失败';

            if (err.message.includes('Cannot read properties of undefined')) {
                errorMessage = 'API对象未正确初始化，请刷新页面重试';
            } else if (err.message.includes('is not a function')) {
                errorMessage = 'API方法不存在，请检查系统配置';
            } else {
                errorMessage = err.message || '未知错误';
            }

            window.showMessage(`提交失败: ${errorMessage}`, true);
        } finally {
            submitting.value = false;
        }
    };

    /**
     * 切换分配状态
     */
    const toggleAssignmentStatus = async (assignment) => {
        const newStatus = assignment.status === 1 ? 2 : 1;
        try {
            const result = await window.FreightApp.api.updateAssignmentStatus(assignment.id, newStatus);
            if (result.code === 0) {
                window.showMessage('状态更新成功');
                loadAssignments();
            } else {
                window.showMessage(result.msg || '状态更新失败', true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        }
    };

    /**
     * 删除单个分配
     */
    const deleteAssignment = async (assignmentId) => {
        if (!assignmentId) {
            window.showMessage('无效的分配ID', true);
            return;
        }

        if (!confirm('确定要删除这个分配吗？')) {
            return;
        }

        try {
            const result = await window.FreightApp.api.deleteAssignment(assignmentId);
            if (result.code === 0) {
                window.showMessage('删除成功');
                loadAssignments();
            } else {
                window.showMessage(result.msg || '删除失败', true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        }
    };

    /**
     * 批量删除分配
     */
    const batchDeleteAssignments = async () => {
        if (selectedAssignmentIds.value.length === 0) {
            window.showMessage('请选择要删除的记录', true);
            return;
        }

        if (!confirm(`确定要删除选中的 ${selectedAssignmentIds.value.length} 条记录吗？`)) {
            return;
        }

        try {
            const result = await window.FreightApp.api.batchDeleteAssignments(selectedAssignmentIds.value);
            if (result.code === 0) {
                window.showMessage(result.msg || '批量删除成功');
                selectedAssignmentIds.value = [];
                loadAssignments();
            } else {
                window.showMessage(result.msg || '批量删除失败', true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        }
    };

    /**
     * 选择所有分配
     */
    const allAssignmentsSelected = computed(() => {
        return assignments.value.length > 0 && selectedAssignmentIds.value.length === assignments.value.length;
    });

    /**
     * 切换所有分配选择
     */
    const toggleAllAssignments = () => {
        if (allAssignmentsSelected.value) {
            selectedAssignmentIds.value = [];
        } else {
            selectedAssignmentIds.value = (assignments.value || []).map(a => a.id);
        }
    };

    /**
     * 关闭分配模态框
     */
    const closeAssignmentModal = () => {
        showAddAssignmentModal.value = false;
        resetAssignmentForm();
    };

    /**
     * 关闭批量分配模态框
     */
    const closeBatchAssignmentModal = () => {
        showBatchAssignmentModal.value = false;
        resetBatchAssignmentForm();
    };

    /**
     * 重置分配表单
     */
    const resetAssignmentForm = () => {
        Object.assign(assignmentForm, {
            warehouseCode: '',
            logisticsCompanyCode: '',
            strategyId: '',
            status: 1
        });
    };

    /**
     * 重置批量分配表单
     */
    const resetBatchAssignmentForm = () => {
        Object.assign(batchAssignmentForm, {
            strategyId: '',
            warehouseCodesText: '',
            logisticsCompanyCodesText: '',
            status: 1
        });
    };

    /**
     * 验证分配表单
     */
    const validateAssignmentForm = () => {
        const errors = [];

        if (!assignmentForm.warehouseCode || assignmentForm.warehouseCode.trim() === '') {
            errors.push('仓库编码不能为空');
        }

        if (!assignmentForm.logisticsCompanyCode || assignmentForm.logisticsCompanyCode.trim() === '') {
            errors.push('物流公司编码不能为空');
        }

        if (!assignmentForm.strategyId) {
            errors.push('请选择策略');
        }

        return {
            isValid: errors.length === 0,
            errors
        };
    };

    /**
     * 验证批量分配表单
     */
    const validateBatchAssignmentForm = () => {
        const errors = [];

        if (!batchAssignmentForm.strategyId) {
            errors.push('请选择策略');
        }

        if (!batchAssignmentForm.warehouseCodesText || batchAssignmentForm.warehouseCodesText.trim() === '') {
            errors.push('请输入仓库编码');
        }

        if (!batchAssignmentForm.logisticsCompanyCodesText || batchAssignmentForm.logisticsCompanyCodesText.trim() === '') {
            errors.push('请输入物流公司编码');
        }

        // 验证仓库编码格式
        const warehouseCodes = batchAssignmentForm.warehouseCodesText
            .split(',')
            .map(code => code.trim())
            .filter(code => code);

        if (warehouseCodes.length === 0) {
            errors.push('请输入有效的仓库编码');
        }

        // 验证物流公司编码格式
        const logisticsCompanyCodes = batchAssignmentForm.logisticsCompanyCodesText
            .split(',')
            .map(code => code.trim())
            .filter(code => code);

        if (logisticsCompanyCodes.length === 0) {
            errors.push('请输入有效的物流公司编码');
        }

        return {
            isValid: errors.length === 0,
            errors
        };
    };

    /**
     * 获取分配状态文本
     */
    const getAssignmentStatusText = (status) => {
        return status === 1 ? '启用' : '禁用';
    };

    /**
     * 获取分配状态类
     */
    const getAssignmentStatusClass = (status) => {
        return status === 1 ? 'status-active' : 'status-inactive';
    };

    /**
     * 根据状态筛选分配
     */
    const filterAssignmentsByStatus = (status) => {
        if (status === null || status === undefined) return assignments.value || [];
        return (assignments.value || []).filter(assignment => assignment.status === status);
    };

    /**
     * 根据策略筛选分配
     */
    const filterAssignmentsByStrategy = (strategyId) => {
        if (!strategyId) return assignments.value || [];
        return (assignments.value || []).filter(assignment => assignment.strategyId === strategyId);
    };

    /**
     * 根据状态获取分配数量
     */
    const getAssignmentsCountByStatus = (status) => {
        return (assignments.value || []).filter(assignment => assignment.status === status).length;
    };

    /**
     * 获取批量分配预览数量
     */
    const getBatchAssignmentPreviewCount = () => {
        const warehouseCount = batchAssignmentForm.warehouseCodesText
            ? batchAssignmentForm.warehouseCodesText.split(',').filter(c => c.trim()).length
            : 0;
        const logisticsCount = batchAssignmentForm.logisticsCompanyCodesText
            ? batchAssignmentForm.logisticsCompanyCodesText.split(',').filter(c => c.trim()).length
            : 0;
        return warehouseCount * logisticsCount;
    };

    /**
     * 根据ID获取策略名称
     */
    const getStrategyName = (strategyId) => {
        const strategy = (strategies.value || []).find(s => s.id === strategyId);
        return strategy ? strategy.name : '未知策略';
    };

    /**
     * 搜索分配 - 调用后端API进行查询
     */
    const searchAssignments = async () => {
        try {
            console.log('执行分配查询，查询条件:', assignmentQuery);

            // 构建查询参数，只传递非空值
            const queryParams = {};
            if (assignmentQuery.warehouseCode) {
                queryParams.warehouseCode = assignmentQuery.warehouseCode;
            }
            if (assignmentQuery.logisticsCompanyCode) {
                queryParams.logisticsCompanyCode = assignmentQuery.logisticsCompanyCode;
            }
            if (assignmentQuery.status !== '') {
                queryParams.status = parseInt(assignmentQuery.status);
            }

            // 调用后端API
            const result = await window.FreightApp.api.getAssignments(queryParams);
            if (result.code === 0) {
                let allAssignments = result.data || [];

                // 加载策略名称
                const strategiesResult = await window.FreightApp.api.getStrategies();
                if (strategiesResult.code === 0) {
                    strategies.value = strategiesResult.data || [];
                    allAssignments.forEach(assignment => {
                        const strategy = (strategies.value || []).find(s => s.id === assignment.strategyId);
                        assignment.strategyName = strategy ? strategy.name : '未知策略';
                    });
                }

                // 如果有策略名称查询，需要在前端进行过滤（因为后端API不支持按策略名称查询）
                if (assignmentQuery.strategyName) {
                    allAssignments = allAssignments.filter(assignment => {
                        const strategyName = getStrategyName(assignment.strategyId);
                        return strategyName.toLowerCase().includes(assignmentQuery.strategyName.toLowerCase());
                    });
                }

                // 总是更新显示数据，即使结果为空数组也要清除当前显示
                assignments.value = allAssignments;
                filteredAssignments.value = allAssignments;

                console.log('分配查询成功，结果数量:', allAssignments.length);
                window.showMessage(`查询成功，找到 ${allAssignments.length} 条记录`);
            } else {
                // API失败时清空数据
                assignments.value = [];
                filteredAssignments.value = [];
                window.showMessage('查询失败: ' + result.msg, true);
            }
        } catch (err) {
            console.error('查询分配失败:', err);
            // 请求异常时清空数据
            assignments.value = [];
            filteredAssignments.value = [];
            window.showMessage('查询失败', true);
        }
    };

    /**
     * 重置查询条件
     */
    const resetAssignmentQuery = () => {
        Object.assign(assignmentQuery, {
            warehouseCode: '',
            logisticsCompanyCode: '',
            strategyName: '',
            status: ''
        });
        // 重置后重新加载所有数据
        loadAssignments();
    };

    /**
     * 获取当前显示的分配数据
     */
    const getDisplayAssignments = () => {
        return filteredAssignments.value.length > 0 ? filteredAssignments.value : assignments.value;
    };

    return {
        // State
        assignments,
        filteredAssignments,
        strategies,
        submitting,
        showAddAssignmentModal,
        showBatchAssignmentModal,
        selectedAssignmentIds,
        assignmentForm,
        batchAssignmentForm,
        assignmentQuery,
        allAssignmentsSelected,

        // Methods
        loadAssignments,
        addAssignment,
        submitAssignment,
        addBatchAssignments,
        submitBatchAssignment,
        toggleAssignmentStatus,
        deleteAssignment,
        batchDeleteAssignments,
        toggleAllAssignments,
        closeAssignmentModal,
        closeBatchAssignmentModal,
        resetAssignmentForm,
        resetBatchAssignmentForm,
        validateAssignmentForm,
        validateBatchAssignmentForm,
        getAssignmentStatusText,
        getAssignmentStatusClass,
        filterAssignmentsByStatus,
        filterAssignmentsByStrategy,
        getAssignmentsCountByStatus,
        getBatchAssignmentPreviewCount,
        getStrategyName,
        searchAssignments,
        resetAssignmentQuery,
        getDisplayAssignments
    };
}
